package com.bsoft.gol.hbs.service.impl;

import com.bsoft.gol.hbs.bean.dto.SimpleMenuDTO;
import com.bsoft.gol.hbs.service.WechatService;
import com.bsoft.gol.hbs.utils.CommonUtils;
import org.atag.util.common.RpcUtil;
import ctd.spring.boot.annotation.SsdevService;
import hcn.exception.ServiceException;
import org.atag.core.model.wechat.SimpleMenu;
import org.atag.util.wechat.MenuUtils;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 微信相关服务实现类
 *
 * @author neoLin - 2022/02/28 14:31
 **/
@SsdevService("wechatService")
public class WechatServiceImpl implements WechatService {

    @Value("${weChat_appId:empty}")
    private String appid;

    @Override
    public SimpleMenuDTO getMenu() {
        SimpleMenu menu = MenuUtils.getMenu(getAccessToken());
        return cpMenu2Dto(menu);
    }

    @Override
    public void createMenu(SimpleMenuDTO dto) {
        SimpleMenu simpleMenu = cpDto2Menu(dto);
        MenuUtils.createMenu(getAccessToken(), simpleMenu);
    }

    private SimpleMenu cpDto2Menu(SimpleMenuDTO dto){
        if(CommonUtils.isEmpty(dto) || CommonUtils.isEmpty(dto.getButton())){
            return null;
        }
        SimpleMenu menu = new SimpleMenu();
        List<SimpleMenu.MainMenu> collect = dto.getButton().stream().map(m -> {
            SimpleMenu.MainMenu button = new SimpleMenu.MainMenu();
            button.setSubButton(m.getSubButton());
            button.setName(m.getName());
            button.setType(m.getType());
            button.setUrl(m.getUrl());
            button.setAppid(m.getAppid());
            button.setPagepath(m.getPagepath());
            return button;
        }).collect(Collectors.toList());

        menu.setButton(collect);
        return menu;
    }

    private SimpleMenuDTO cpMenu2Dto(SimpleMenu menu){
        if(CommonUtils.isEmpty(menu) || CommonUtils.isEmpty(menu.getButton())){
            return null;
        }
        SimpleMenuDTO dto = new SimpleMenuDTO();
        List<SimpleMenuDTO.Button> collect = menu.getButton().stream().map(m -> {
            SimpleMenuDTO.Button button = new SimpleMenuDTO.Button();
            button.setSubButton(m.getSubButton());
            button.setName(m.getName());
            button.setType(m.getType());
            button.setUrl(m.getUrl());
            button.setAppid(m.getAppid());
            button.setPagepath(m.getPagepath());
            return button;
        }).collect(Collectors.toList());

        dto.setButton(collect);
        return dto;
    }

    /**
     * 获取accessToken
     */
    private String getAccessToken(){
        String accessToken = RpcUtil.invoke("hcn.weChatService", "getAccessToken", appid);
        if(CommonUtils.isEmpty(accessToken)){
            throw new ServiceException("获取accessToken失败");
        }
        return accessToken;
    }
}
